import axios from 'axios'
import store from '@/vuex/index'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

//重新封装axios
const service = axios.create({
    // baseURL: 'http://localhost:8088',
    baseURL: '/api',
    //设置异步超时5秒
    timeout: 5000
})

//设置请求拦截
service.interceptors.request.use(
    config => {
        //这里多层嵌套导入是没有提示的
        //2层header判断
        // if (store.getters.token) {
        //     config.headers['token'] = store.getters.token
        // }else 
        if(getToken()){
            config.headers['token'] = getToken()
        }
        return config
    },
    error => {
        console.log('请求发送报错:' + error)
    }
)

service.interceptors.response.use(
    response => {
        const res = response.data
        //请求失败--提示错误
        if (res.code !== 20000) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duraiton: 5 * 1000
            })

            return Promise.reject(new Error(res.message || 'Error'))
        }
        //如果成功把值返回
        return response
    },
    error => {
           // 对于网络异常、超时等非业务错误，也在这里统一处理
        console.log('err' + error)
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000 
        })
        return Promise.reject(error)
    }
)

export default service